import 'package:dio/dio.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// This interceptor is used to show request and response logs
/// to debug network request and response
class LoggerInterceptor extends Interceptor {
  Logger logger = Logger(
      printer: PrettyPrinter(
    methodCount: 0,
    colors: true,
    printEmojis: true,
  ));

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    final options = err.requestOptions;
    final requestPath = '${options.baseUrl}${options.path}';
    logger.e('${options.method} request ===> $requestPath'); // err log format
    logger.d('Error type: ${err.error}\r\n'
        'Error message: ${err.message}\r\n'); // debug log format
    handler.next(err); // continue with the error
  }

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    final requestPath = '${options.baseUrl}${options.path}';
    logger.i('${options.method} request ==> $requestPath'); // info log format
    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    logger.d('Status code: ${response.statusCode}\r\n'
        'Status message: ${response.statusMessage}\r\n'
        'Headers: ${response.headers}\r\n'
        'Data: ${response.data}\r\n'); // debug log format
    handler.next(response); // continue with the response
  }
}

// Auth utils when request
class AuthorizationInterceptor extends Interceptor {
  @override
  void onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    final SharedPreferences sharedPreferences =
        await SharedPreferences.getInstance();
    // auth by token
    final token = sharedPreferences.getString('token');
    options.headers['Authorization'] = "Bearer $token";
    handler.next(options); // then request
  }
}
// DONE